package com.example.demo.app;

import com.example.demo.ChatMemory.FileBasedChatMemory;
import com.example.demo.ChatMemory.KryoFileChatMemory;
import com.example.demo.advisor.MyCustomAdvisor;
import com.example.demo.advisor.ReReadingAdvisor;
import com.example.demo.model.dto.ai.LoveReport;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.ai.chat.client.advisor.vectorstore.QuestionAnswerAdvisor;
import org.springframework.ai.chat.memory.InMemoryChatMemoryRepository;
import org.springframework.ai.chat.memory.MessageWindowChatMemory;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.tool.ToolCallback;
import org.springframework.ai.tool.ToolCallbackProvider;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.stereotype.Service;


@Service
@Slf4j
public class LoveApp {

    @Resource
    private VectorStore loveAppVectorStore;

    @Resource
    private ToolCallback[] allTools;

    @Resource
    private ToolCallbackProvider toolCallbackProvider;

    private static final String STORAGE_PATH = "./chat-memory-storage";
    private final ChatClient chatClient;

    private static final String SYSTEM_PROMPT = "扮演深耕恋爱心理领域的专家。开场向用户表明身份，告知用户可倾诉恋爱难题。" +
            "围绕单身、恋爱、已婚三种状态提问：单身状态询问社交圈拓展及追求心仪对象的困扰；" +
            "恋爱状态询问沟通、习惯差异引发的矛盾；已婚状态询问家庭责任与亲属关系处理的问题。" +
            "引导用户详述事情经过、对方反应及自身想法，以便给出专属解决方案。";

    public LoveApp(ChatModel dashscopeChatModel) {
        MessageWindowChatMemory chatMemory = MessageWindowChatMemory.builder()
                .chatMemoryRepository(new InMemoryChatMemoryRepository())
                .maxMessages(5)
                .build();
        String fileDir = System.getProperty("user.dir") + "/chat-memory";
        chatClient = ChatClient.builder(dashscopeChatModel)
                .defaultSystem(SYSTEM_PROMPT + "每次对话后都要生成恋爱结果，标题为{用户名}的恋爱报告，内容为建议列表")
                .defaultAdvisors(
                        MessageChatMemoryAdvisor.builder(new KryoFileChatMemory(STORAGE_PATH)).order(0).build(),
                        new MyCustomAdvisor(),
                        new ReReadingAdvisor()
                )
                .build();
    }

    //    public LoveApp(@Qualifier("openAiChatClient") ChatClient openAiChatClient) {
//        chatClient = openAiChatClient;
//    }
//
    public LoveReport doChat(String message, String chatId) {
        LoveReport loveReport = chatClient
                .prompt()
                .user(message)
                .advisors(spec -> spec
                        .param("chat_memory_conversation_id", chatId)
                        .param("chat_memory_response_size", 10))
                .call()
                .entity(LoveReport.class);
        //String content = response.getResult().getOutput().getText();
        log.info("response: {}", loveReport);
        return loveReport;
    }

    public LoveReport doChatWithRAG(String message, String chatId) {
        LoveReport loveReport = chatClient
                .prompt()
                .user(message)
                .advisors(spec -> spec
                        .param("chat_memory_conversation_id", chatId)
                        .param("chat_memory_response_size", 10))
                .advisors(new QuestionAnswerAdvisor(loveAppVectorStore))
                .call()
                .entity(LoveReport.class);
        //String content = response.getResult().getOutput().getText();
        log.info("response: {}", loveReport);
        return loveReport;
    }


    public String doChatWithTools(String message, String chatId) {
        ChatResponse response = chatClient
                .prompt()
                .user(message)
                .advisors(spec -> spec
                        .param("chat_memory_conversation_id", chatId)
                        .param("chat_memory_response_size", 10))
                .toolCallbacks(allTools)
                .call()
                .chatResponse();
        String content = response.getResult().getOutput().getText();
        log.info("content: {}", content);
        return content;
    }

    public String doChatWithMCPToolsAndRAG(String message, String chatId) {
        ChatResponse response = chatClient
                .prompt()
                .user(message)
                .advisors(spec -> spec
                        .param("chat_memory_conversation_id", chatId)
                        .param("chat_memory_response_size", 10))
                .toolCallbacks(toolCallbackProvider)
                .call()
                .chatResponse();
        String content = response.getResult().getOutput().getText();
        log.info("content: {}", content);
        return content;
    }


}

